<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        placeholder="请输入搜索内容"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select
        v-model="listQuery.type"
        placeholder="搜索类型"
        clearable
        class="filter-item"
        style="width: 130px"
      >
        <el-option
          v-for="item in searchTypeOptions"
          :key="item.key"
          :label="item.display_name+'('+item.key+')'"
          :value="item.key"
        />
      </el-select>
      <el-select
        v-model="listQuery.sort"
        style="width: 140px"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option
          v-for="item in sortOptions"
          :key="item.key"
          :label="item.label"
          :value="item.key"
        />
      </el-select>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >搜索</el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >新增</el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column
        label="ID"
        prop="_id"
        sortable="custom"
        align="center"
        width="200"
        :class-name="getSortClass('_id')"
      >
        <template slot-scope="{row}">
          <span>{{ row._id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生产日期" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.date | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="保质期" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.warranty | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品名" min-width="150px" align="center">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.name }}</span>
          <el-tag>{{ row.type | typeFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="商品图片" min-width="150px" align="center">
        <template slot-scope="{row}">
          <el-image 
          style="height:100px" 
          :src="imgsUrl+row.imgs[0]"

          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="商品分类" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.clazz }}</span>
        </template>
      </el-table-column>
      <el-table-column label="材质" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.material }}</span>
        </template>
      </el-table-column>
      <el-table-column label="制作方法" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.method }}</span>
        </template>
      </el-table-column>
      <el-table-column label="适用规格" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.standard }}</span>
        </template>
      </el-table-column>
      <el-table-column label="独家" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.exclusive }}</span>
        </template>
      </el-table-column>
      <el-table-column label="口味" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.flavor }}</span>
        </template>
      </el-table-column>
      <el-table-column label="特殊功用" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.special }}</span>
        </template>
      </el-table-column>
      <el-table-column label="产地" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.origin }}</span>
        </template>
      </el-table-column>
      <el-table-column label="特色" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.feature }}</span>
        </template>
      </el-table-column>
      <el-table-column label="包装" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.packing }}</span>
        </template>
      </el-table-column>
      <el-table-column label="价格" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="库存" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.count }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="110px" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.status">{{row.status=='1'?"上架":"下架"}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">修改</el-button>
          <el-button
            v-if="row.status=='0'"
            size="mini"
            type="success"
            @click="handleModifyStatus(row,'1')"
          >上架</el-button>
          <el-button 
          v-if="row.status=='1'" 
          size="mini" 
          @click="handleModifyStatus(row,'0')"
          >下架</el-button>
          <el-button
            v-if="row.status!='deleted'"
            size="mini"
            type="danger"
            @click="handleDelete(row,$index)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :curPage.sync="listQuery.curPage"
      :eachPage.sync="listQuery.eachPage"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="80px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="类型" prop="type">
          <el-select v-model="temp.type" class="filter-item" placeholder="请选择">
            <el-option
              v-for="item in calendarTypeOptions"
              :key="item.key"
              :label="item.display_name"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品名" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="商品分类" prop="clazz">
          <el-input v-model="temp.clazz" />
        </el-form-item>
        <el-form-item label="材质" prop="material">
          <el-input v-model="temp.material" />
        </el-form-item>
        <el-form-item label="制作方法" prop="method">
          <el-input v-model="temp.method" />
        </el-form-item>
        <el-form-item label="适用规格" prop="standard">
          <el-input v-model="temp.standard" placeholder="如有多个，请用逗号分开" />
        </el-form-item>
        <el-form-item label="独家权限" prop="exclusive">
          <el-input v-model="temp.exclusive" />
        </el-form-item>
        <el-form-item label="包装规格" prop="packing">
          <el-input v-model="temp.packing" placeholder="如有多个，请用逗号分开" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="temp.price" placeholder="如有多个，请用逗号分开" />
        </el-form-item>
        <el-form-item label="口味" prop="flavor">
          <el-input v-model="temp.flavor" placeholder="如有多个，请用逗号分开" />
        </el-form-item>
        <el-form-item label="特殊功用" prop="special">
          <el-input v-model="temp.special" />
        </el-form-item>
        <el-form-item label="产地" prop="origin">
          <el-input v-model="temp.origin" />
        </el-form-item>
        <el-form-item label="生产日期" prop="date">
          <el-date-picker v-model="temp.date" type="datetime" placeholder="请选择一个日期" />
        </el-form-item>
        <el-form-item label="保质期" prop="warranty">
          <el-date-picker v-model="temp.warranty" type="datetime" placeholder="请选择一个日期" />
        </el-form-item>
        <el-form-item label="特色" prop="feature">
          <el-input v-model="temp.feature" />
        </el-form-item>
        <el-form-item label="库存" prop="count">
          <el-input v-model="temp.count" />
        </el-form-item>
        <el-form-item label="图片上传">
          <el-upload
            class="upload-demo"
            action="/api/supplierFoods/upload"
            :on-success="handleSuccess"
            :on-remove="handleRemove"
            :file-list="fileList"
            list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getFoods,
  addFood,
  removeFood,
  updateFoods
} from "@/api/zjm_supplierFoods";
import waves from "@/directive/waves"; // waves directive
import { parseTime } from "@/utils";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination

const searchTypeOptions = [
  { key: "name", display_name: "商品名" },
  { key: "type", display_name: "商品类型" },
  { key: "status", display_name: "商品状态" },
  { key: "clazz", display_name: "商品分类" },
  { key: "material", display_name: "材质" },
  { key: "method", display_name: "制作方法" },
  { key: "standard", display_name: "适用规格" },
  { key: "exclusive", display_name: "独家" },
  { key: "flavor", display_name: "口味" },
  { key: "special", display_name: "特殊功用" },
  { key: "origin", display_name: "产地" },
  { key: "feature", display_name: "特色" },
  { key: "packing", display_name: "包装" },
  { key: "price", display_name: "价格" }
];
const calendarTypeOptions = [
  { key: "主粮", display_name: "主粮" },
  { key: "洗浴", display_name: "洗浴" },
  { key: "日用品", display_name: "日用品" },
  { key: "零食", display_name: "零食" },
  { key: "保健品", display_name: "保健品" },
  { key: "医疗", display_name: "医疗" },
  { key: "清洁洗护", display_name: "清洁洗护" },
  { key: "玩具", display_name: "玩具" }
];

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name;
  return acc;
}, {});

export default {
  name: "ComplexTable",
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "info",
        deleted: "danger"
      };
      return statusMap[status];
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type];
    }
  },
  data() {
    return {
      fileList: [],
      imgsUrl: "http://localhost:3001",
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        curPage: 1,
        eachPage: 20,
        name: undefined,
        type: undefined,
        sort: +1
      },
      calendarTypeOptions,
      searchTypeOptions,
      sortOptions: [
        { label: "ID 升序", key: +1 },
        { label: "ID 降序", key: -1 }
      ],
      temp: {
        date: "", //生产日期
        name: "", //商品名
        type: "", //商品类型
        status:"1", //商品状态
        clazz: "", //商品分类
        material: "", //材质
        method: "", //制作方法
        standard: "", //适用规格
        exclusive: "", //独家
        flavor: "", //口味
        special: "", //特殊功用
        origin: "", //产地
        warranty: "", //保质期
        feature: "", //特色
        packing: "", //包装
        price: "", //价格，如有多个与包装顺序对应
        imgs: [
          //图片，一张大图，一张小图
          // big: [],
          // small: []
        ],
        count:"0"
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "修改",
        create: "新增"
      },
      dialogPvVisible: false,
      rules: {
        type: [{ required: true, message: "类型不能为空", trigger: "change" }],
        date: [
          {
            required: true,
            message: "生产日期不能为空",
            trigger: "change"
          }
        ],
        warranty: [
          {
            required: true,
            message: "保质期不能为空",
            trigger: "change"
          }
        ],
        name: [{ required: true, message: "商品名不能为空", trigger: "blur" }],
        clazz: [
          { required: true, message: "商品分类不能为空", trigger: "blur" }
        ],
        material: [
          { required: true, message: "材质不能为空", trigger: "blur" }
        ],
        method: [
          { required: true, message: "制作方法不能为空", trigger: "blur" }
        ],
        standard: [
          { required: true, message: "适用规格不能为空", trigger: "blur" }
        ],
        exclusive: [
          { required: true, message: "独家不能为空", trigger: "blur" }
        ],
        flavor: [{ required: true, message: "口味不能为空", trigger: "blur" }],
        special: [
          { required: true, message: "特殊功用不能为空", trigger: "blur" }
        ],
        origin: [{ required: true, message: "产地不能为空", trigger: "blur" }],
        feature: [{ required: true, message: "特色不能为空", trigger: "blur" }],
        packing: [{ required: true, message: "包装不能为空", trigger: "blur" }],
        price: [{ required: true, message: "价格不能为空", trigger: "blur" }],
        count: [{ required: true, message: "价格不能为空", trigger: "blur" }]
      }
    };
  },
  created() {
    this.getList();

  },
  methods: {
    handleRemove(file, fileList) {
      this.temp.imgs.map((v, i) => {
        if (v == file.name) {
          this.temp.imgs.splice(i, 1);
        }
      });
    },
    handleSuccess(response, file, fileList) {
      //图片上传成功
      this.temp.imgs.push(response);
    },
    async getList() {
      //获取货品列表
      this.listLoading = true;
      let data = await getFoods(this.listQuery);
      data.rows.map(v => {
        v.standard = v.standard.join(",");
        v.packing = v.packing.join(",");
        v.flavor = v.flavor.join(",");
        v.price = v.price.join(",");
      });
      this.list = data.rows;
      this.total = data.total;
      setTimeout(() => {
        this.listLoading = false;
      }, 1000);
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    async handleModifyStatus(row, status) {
      this.$message({
        message: "操作成功",
        type: "success"
      });
      row.status = status;
      await updateFoods(row);
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "_id") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "descending") {
        this.listQuery.sort = -1;
      } else {
        this.listQuery.sort = +1;
      }
      this.handleFilter();
    },
    resetTemp() {
      this.temp = {
        date: "", //生产日期
        name: "", //商品名
        type: "", //商品类型
        status:"1", //商品状态
        class: "", //商品分类
        material: "", //材质
        method: "", //制作方法
        standard: "", //适用规格
        exclusive: "", //独家
        flavor: "", //口味
        special: "", //特殊功用
        origin: "", //产地
        warranty: "", //保质期
        feature: "", //特色
        packing: "", //包装
        price: "", //价格，如有多个与包装顺序对应
        imgs: [
          //图片，一张大图，一张小图
          // big: [],
          // small: []
        ],
        count:"0" //库存
      };
    },
    handleCreate() {
      //点击新增
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    createData() {
      //新增货品
      this.$refs["dataForm"].validate(async valid => {
        if (valid) {
          let data = await addFood(this.temp);
          this.dialogFormVisible = false;
          this.$notify({
            title: "成功",
            message: "新增成功",
            type: "success",
            duration: 2000
          });
        }
        this.getList();
      });
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.fileList = this.temp.imgs.map(v => {
        return {
          name: v,
          url: this.imgsUrl + v
        };
      });
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData() {
      this.$refs["dataForm"].validate(async valid => {
        if (valid) {
          await updateFoods(this.temp);
          this.dialogFormVisible = false;
          this.$notify({
            title: "成功",
            message: "修改成功",
            type: "success",
            duration: 2000
          });
          this.getList();
        }
      });
    },
    handleDelete(row, index) {
      //删除
      this.$notify({
        title: "成功",
        message: "删除成功",
        type: "success",
        duration: 2000
      });
      removeFood(row._id);
      this.getList();
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort;
      return sort === `+${key}` ? "+1" : "-1";
    }
  }
};
</script>
